package com.baidu.fengchao.broad.view;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.nutz.mvc.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaojiangang
 * Date: 13-5-2
 * Time: 下午10:42
 */
public class FreeMarkerView implements View{
    private Configuration configuration;

    public FreeMarkerView() throws IOException {
        configuration = new Configuration();
        configuration.setDirectoryForTemplateLoading(new File(this.getClass().getClassLoader().getResource("ftl").getFile()));
    }
    @Override
    public void render(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Throwable {
        String path = httpServletRequest.getServletPath();
        String filename = path.substring(path.lastIndexOf("/")+1,path.lastIndexOf("."))+".ftl";
        Template template = configuration.getTemplate(filename,"utf8");
        template.process(o,httpServletResponse.getWriter());
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
